package com.example.demo.utils;


import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MqttUtils {
    public static String getMessage;
    private static MqttClient mqttClient;


    /**
     * 连接mqtt
     * @param host
     * @param clientId
     * @param subscribeTopic
     * @return
     * @throws MqttException
     */
    public static MqttClient mqttConnect(String host, String clientId, String subscribeTopic) throws MqttException {
        mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
        mqttClient.setTimeToWait(10000);
        mqttClient.connect(getOptions());
        mqttClient.subscribe(subscribeTopic, 2);
        mqttClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean b, String s) {
                System.out.println("connectComplete");
            }

            @Override
            public void connectionLost(Throwable throwable) {
                System.out.println("connectionLost");
            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                getMessage = new String(mqttMessage.getPayload());//获取回调结果，仅支持单数据展示
                log.info("获取服务器返回结果：" + getMessage);
                disconnect();
            }

            public void disconnect() throws MqttException {
                if (mqttClient!=null && mqttClient.isConnected()){
                    log.info("----关闭mqtt连接-----");
                    mqttClient.disconnect();
                    mqttClient.close();
                    mqttClient = null;
                }
            }


            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                System.out.println("deliveryComplete");
            }
        });
        return mqttClient;
    }

    /**
     * 连接主题，发布消息
     * @param mqttClient
     * @param publishTopic
     * @param message
     */
    public static void mqttPublish(MqttClient mqttClient, String publishTopic, String message) {
        try {
            log.info("发送一次mqtt请求：" + message);
            mqttClient.publish(publishTopic, message.getBytes(), 0, false);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取回调数据
     * @return
     */
    public static String getCaLLBackMessage() {
        System.out.println("这是获取测试message:" + getMessage);
        return getMessage;
    }

    /**
     * @return
     */
    public static MqttConnectOptions getOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        //设置session 是否保留上一条记录
        options.setCleanSession(false);
        //连接超时时间
        options.setConnectionTimeout(10);
        //心跳会话时间
        options.setKeepAliveInterval(60);
        //自动重连
        options.setAutomaticReconnect(false);
        return options;
    }
}
